//
//  YFunctionViewController.m
//  shijianpinggu
//
//  Created by apple on 2017/11/6.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "YFunctionViewController.h"
#import "FunctionTableViewCell.h"
#import "ChangePwViewController.h"
#import "ExitTableViewCell.h"

@interface YFunctionViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (weak, nonatomic) IBOutlet UITableView *tableView;

@end

@implementation YFunctionViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"设置";
    //去掉cell多余分割线
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    
    
    //解决tabbleview底部被遮挡问题
    if (([[[UIDevice currentDevice] systemVersion] doubleValue] >= 7.0)) {
        self.edgesForExtendedLayout = UIRectEdgeNone;
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    
    
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"FunctionTableViewCell" bundle:nil] forCellReuseIdentifier:@"FunctionTableViewCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"ExitTableViewCell" bundle:nil] forCellReuseIdentifier:@"ExitTableViewCell"];
    
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return 1;
    }else if(section == 1){
        return 3;
    }else{
        return 1;
    }
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    static NSString * identy = @"headFoot";
    
    
    
    UITableViewHeaderFooterView * hf = [tableView dequeueReusableHeaderFooterViewWithIdentifier:identy];
    
    if (!hf) {
        
        NSLog(@"%li",section);
        
        hf = [[UITableViewHeaderFooterView alloc]initWithReuseIdentifier:identy];
        
        UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 40)];
        view.backgroundColor = [UIColor colorWithRed:244/255.0 green:244/255.0 blue:244/255.0 alpha:1];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(12, 0, 300, 40)];
        label.font = [UIFont systemFontOfSize:12];
        label.textColor = [UIColor colorWithRed:76/255.0 green:76/255.0 blue:76/255.0 alpha:1];
        if (section == 0) {
            label.text = @"系统设置";
        }else if(section == 1){
            label.text = @"其它";
        }
        [view addSubview:label];
        
        [hf addSubview:view]; //(若将此注释：view未添加)
        
    }
    
    // hf.contentView.backgroundColor = [UIColor purpleColor];（去掉此行注释：可设置hf。contentView背景色），若此行和上一行都不注释，显示红色
    
    return hf;
    
    
    
   
}




- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    if (indexPath.section == 1 && indexPath.row == 2) {
        FunctionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ExitTableViewCell" forIndexPath:indexPath];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }else{
       FunctionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"FunctionTableViewCell" forIndexPath:indexPath];
           cell.selectionStyle = UITableViewCellSelectionStyleNone;
       if (indexPath.section == 0) {
           if (indexPath.row == 0) {
            cell.titleLabel.text = @"手势密码";
            [cell.switchButton addTarget:self action:@selector(switchButtonAction:) forControlEvents:UIControlEventTouchUpInside];
               NSInteger gestureS = [[[NSUserDefaults standardUserDefaults] objectForKey:@"gestureState"] integerValue];
               if (gestureS == 1) {
                  [cell.switchButton setOn:YES animated:YES];
               }else if(gestureS == 2){
                   [cell.switchButton setOn:NO animated:YES];
               }
               
               
          }
          }else{
            cell.switchButton.hidden = YES;
           if (indexPath.row == 0) {
            cell.titleLabel.text = @"修改手势密码";
          }else{
            cell.titleLabel.text = @"修改密码";
          }
      }
           return cell;
    }
    
}
-(void)switchButtonAction:(UISwitch *)switchButton{
    NSInteger swSetate;
    if (switchButton.isOn == YES) {
        swSetate = 0;
    }else{
        swSetate = 1;
    }
    NSDictionary *dict = @{@"contactid":[[NSUserDefaults standardUserDefaults] objectForKey:@"userid"],@"isgesture":[NSString stringWithFormat:@"%ld",(long)swSetate]};
    
    // 初始化Manager
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    // 不加上这句话，会报“Request failed: unacceptable content-type: text/plain”错误，因为我们要获取text/plain类型数据
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    //    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];//如果报接受类型不一致请替换一致text/html或别的
    manager.requestSerializer=[AFJSONRequestSerializer serializer];//申明请求的数据是json类型
    // post请求
    
    [manager POST:@"http://wangan.ldynet.cn/index.php/IndexAppSet/isgesture" parameters:dict constructingBodyWithBlock:^(id  _Nonnull formData) {
        // 拼接data到请求体，这个block的参数是遵守AFMultipartFormData协议的。
        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        // 这里可以获取到目前的数据请求的进度
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        // 请求成功，解析数据
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves error:nil];
        NSLog(@"1111%@", dic);
        
        if ([dic[@"isgesture"] integerValue] == 0) {
            [[NSUserDefaults standardUserDefaults] setObject:@1 forKey:@"gestureState"];
        }else{
            [[NSUserDefaults standardUserDefaults] setObject:@2 forKey:@"gestureState"];
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];

    
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 1 && indexPath.row == 2) {
        return 142;
    }else{
        return 64;
    }
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            if ([WUGesturesUnlockViewController gesturesPassword].length > 0) {
                WUGesturesUnlockViewController *vc = [[WUGesturesUnlockViewController alloc] initWithUnlockType:WUUnlockTypeValidatePwd];
                vc.setup = @"setup";
                [self presentViewController:vc animated:YES completion:nil];
            }else {
//                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:nil message:@"还没有设置手势密码" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"ok", nil];
//                [alertView show];
                WUGesturesUnlockViewController *vc = [[WUGesturesUnlockViewController alloc] initWithUnlockType:WUUnlockTypeCreatePwd];
                vc.setup = @"setup";
                [self presentViewController:vc animated:YES completion:nil];
            }

        }else{
            ChangePwViewController *chagepw = [ChangePwViewController new];
            [self showViewController:chagepw sender:nil];
        }
    }
}

@end
